<template>
  <div class="department-container">
    <div class="app-container">
      <el-card>
        <!-- 用一个行列布局 -->
        <el-row type="flex" justify="space-between" align="middle" style="height: 40px">
          <el-col :span="20">
            <span>江苏传智播客教育科技股份有限公司</span>
          </el-col>
          <el-col :span="4">
            <el-row type="flex" justify="end">
              <!-- 两个内容 -->
              <el-col>负责人</el-col>
              <el-col>操作</el-col>
            </el-row>
          </el-col>
        </el-row>
        <!-- 树形组件 -->
        <el-tree :data="list" :props="defaultProps" :default-expand-all="true">
          <template #default="{ data }">
            <el-row
              type="flex"
              justify="space-between"
              align="middle"
              style="height: 40px; width: 100%;"
            >
              <el-col :span="20">
                <span>{{ data.name }}</span>
              </el-col>
              <el-col :span="4">
                <el-row type="flex" justify="end">
                  <!-- 两个内容 -->
                  <el-col>{{ data.manager }}</el-col>
                  <el-col>
                    <!-- 下拉菜单 element -->
                    <el-dropdown>
                      <span> 操作<i class="el-icon-arrow-down" /> </span>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item @click.native="addDepart(data.id)">添加子部门</el-dropdown-item>
                        <el-dropdown-item @click.native="editDepart(data.id)">编辑部门</el-dropdown-item>
                        <el-dropdown-item @click.native="delDepart(data.id)">删除部门</el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-tree>
      </el-card>
    </div>
    <!-- 放置新增弹框 -->
    <el-dialog
      title="提示"
      :visible="dialogVisible"
      width="30%"
      @close="closeDialog"
      @open="openDialog"
    >
      <template #default>
        <el-form ref="addForm" label-width="120px" :model="form" :rules="rules">
          <el-form-item label="部门名称" prop="name">
            <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
          </el-form-item>
          <el-form-item label="部门编码" prop="code">
            <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
          </el-form-item>
          <el-form-item label="部门负责人" prop="manager">
            <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
              <el-option
                v-for="item in managerList"
                :key="item.id"
                :label="item.username"
                :value="item.username"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="部门介绍" prop="introduce">
            <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" />
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { fetchDepartmentList, fetchManagerList, fetchAddDepart, fetchDelDepart, fetchDetail, fetchUpdateDepart } from '@/api/department'
import transTree from '@/utils/transTree'

export default {
  name: 'Department',
  data() {
    var validateCode = async(rule, value, callback) => {
      // 获取所有数据(包含code)
      const res = await fetchDepartmentList()

      // 1、将所有的code单独放入一个数组
      let newArr = []

      if (this.form.id) {
        // 编辑状态下需要去掉自己的code码,直接去掉自己的那一项
        const newCode = res.depts.filter(item => item.id !== this.form.id)
        newArr = newCode.map(item => item.code)
      } else {
        newArr = res.depts.map(item => item.code)
      }

      // console.log(newArr)
      // 2、进行查找，是否重复
      if (newArr.includes(value)) {
        callback(new Error('当前code码值重复'))
      } else {
        callback()
      }
    }
    return {
      list: [{
        name: '财务部',
        manager: '张三',
        children: [
          {
            name: '财务核算部',
            manager: '李四'
          },
          {
            name: '税务核算部',
            manager: '王五'
          }
        ]
      }],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      dialogVisible: false,
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: '',
        pid: ''
      },
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: ['blur', 'change'] }
        ],
        code: [
          { validator: validateCode, trigger: ['blur', 'change'] },
          { required: true, message: '部门编码不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: ['blur', 'change'] }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: ['blur', 'change'] }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: ['blur', 'change'] }
        ]
      },
      managerList: []
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    async getList() {
      const res = await fetchDepartmentList()
      this.list = transTree(res.depts)
      console.log(res.depts)
    },
    // 新增部门
    addDepart(id) {
      this.form.pid = id
      this.dialogVisible = true
    },
    // 关闭前的回调函数
    closeDialog() {
      this.dialogVisible = false
      this.$refs.addForm.resetFields()
    },
    // 打开前的回调函数
    async openDialog() {
      const res = await fetchManagerList()
      this.managerList = res
    },
    // 最终确定表单验证
    confirm() {
      this.$refs.addForm.validate(async(valid) => {
        if (valid) {
          if (this.form.id) {
            await fetchUpdateDepart(this.form)
          } else {
            await fetchAddDepart(this.form)
          }

          this.$message.success(`${this.form.id ? '编辑' : '新增'}部门成功`)
          this.dialogVisible = false
          this.getList()
          this.$refs.addForm.resetFields()
          this.resetForm()
        }
      })
    },
    // 编辑部门
    async editDepart(id) {
      this.dialogVisible = true
      const res = await fetchDetail(id)
      this.form = res
    },
    // 编辑时候重置id
    resetForm() {
      this.form = {
        name: '',
        code: '',
        manager: '',
        introduce: '',
        pid: ''
      }
    },
    // 删除部门
    delDepart(id) {
      this.$confirm('确认删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await fetchDelDepart(id)
        this.getList()
        this.$message.success('')
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>
